package com.leonzx.base.service.system;

import com.leonzx.base.dao.system.ChatBodyDAO;
import com.leonzx.base.service.BaseService;
import com.leonzx.base.utils.SQLUtils;
import com.leonzx.base.utils.UUIDUtils;
import org.apache.commons.lang3.StringUtils;
import org.jim.common.packets.ChatBody;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;

/**
 * @Author:梁亮
 * @Description:
 * @Date: 2018/7/5 10:33
 */
@Service
public class ChatBodyService extends BaseService {
    @Autowired
    private ChatBodyDAO chatBodyDAO;

    /**
     * 保存消息到数据库
     * @param chatBody
     */
    public void save(ChatBody chatBody) {
        com.leonzx.base.entity.system.ChatBody saveChatBody = new com.leonzx.base.entity.system.ChatBody();
        saveChatBody.setId(UUIDUtils.getUUID());
        saveChatBody.setFrom_id(chatBody.getFrom());
        saveChatBody.setCreateUserId(chatBody.getFrom());
        saveChatBody.setTo_id(chatBody.getTo());
        saveChatBody.setMsg_type(Integer.toString(chatBody.getMsgType()));
        saveChatBody.setChat_type(Integer.toString(chatBody.getChatType()));
        saveChatBody.setContent(chatBody.getContent().split("%")[0]);
        String groupId ="";
        if(StringUtils.isNotBlank(chatBody.getGroup_id())){
            groupId = chatBody.getGroup_id();
        }
        saveChatBody.setGroup_id(groupId);
        saveChatBody.setCmd(Integer.toString(chatBody.getCmd()));
        saveChatBody.setCreateTime(new Date());
        saveChatBody.setJson("");
        chatBodyDAO.insert(saveChatBody);
    }

    public List<com.leonzx.base.entity.system.ChatBody> getAllBaseChatBodys(com.leonzx.base.entity.system.ChatBody chatBody) {
        Example example = new Example(com.leonzx.base.entity.system.ChatBody.class);
        Example.Criteria criteria = example.createCriteria();
        if (StringUtils.isNotBlank(chatBody.getGroup_id())) {
            criteria.andLike("group_id", SQLUtils.like(chatBody.getGroup_id()));
        }
        if (StringUtils.isNotBlank(chatBody.getTo_id())) {
            criteria.andLike("to_id", SQLUtils.like(chatBody.getTo_id()));
        }
        if(StringUtils.isNotBlank(chatBody.getMsg_type())){
            criteria.andLike("msg_type", SQLUtils.like(chatBody.getMsg_type()));
        }
        return chatBodyDAO.selectByExample(example);

    }

    public List<com.leonzx.base.entity.system.ChatBody> getFriendDataByFromIdAndToId(com.leonzx.base.entity.system.ChatBody chatBody) {
        return chatBodyDAO.getFriendDataByFromIdAndToId(chatBody);
    }

    public List<com.leonzx.base.entity.system.ChatBody> getGroupDataByGroupId(com.leonzx.base.entity.system.ChatBody chatBody) {
        return chatBodyDAO.getGroupDataByGroupId(chatBody);

    }
}
